package org.example.project.common.middleware.controller;

import org.example.project.common.contant.R;
import org.example.project.common.middleware.constant.ApiRequestMapping;
import org.example.project.common.middleware.controller.vo.RedisNode;
import org.example.project.common.middleware.service.RedisService;
import org.example.project.common.middleware.service.dto.RedisDTO;
import org.example.project.common.web.RestCrudController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author wenxy
 * @date 2020/10/9
 */
@RestController
@RequestMapping(ApiRequestMapping.REDIS_API)
@ConditionalOnClass(RedisTemplate.class)
public class RedisApiController implements RestCrudController<RedisDTO, String> {

    @Autowired
    RedisService defaultRedisService;

    @Override
    public R<RedisDTO> getById(String s) {
        return R.success(RedisDTO.of(s, defaultRedisService.get(s)));
    }

    @Override
    public R<String> removeById(String s) {
        return R.success(String.valueOf(defaultRedisService.delete(Collections.singleton(s))));
    }

    @Override
    public R<String> save(RedisDTO redisDTO) {
        defaultRedisService.set(redisDTO.getKey(), redisDTO.getValue());
        return R.success();
    }

    @Override
    public R<String> updateById(RedisDTO redisDTO, String key) {
        return R.success(String.valueOf(defaultRedisService.setIfPresent(redisDTO.getKey(), redisDTO.getValue())));
    }

    @GetMapping("/cluster/slaves")
    public R<Collection> getSlaves(RedisNode redisNode) {
        return R.success(defaultRedisService.getSlaves(redisNode));
    }

    @GetMapping("/cluster/clients")
    public R<List> getClientListInfos() {
        return R.success(defaultRedisService.getClientListInfos());
    }

    @GetMapping("/type/{key}")
    public R<String> getType(@PathVariable String key) {
        return R.success(defaultRedisService.type(key));
    }

    @GetMapping("/exists/{key}")
    public R<Boolean> exists(@PathVariable String key) {
        return R.success(defaultRedisService.hasKey(key));
    }

}
